import { useEffect } from "react";

export default function useClickAway(
    onClickAway: () => void,
    target: HTMLDivElement[],
    eventName = 'click',
    useCapture: boolean,
    isListener?: boolean,
    outerVar?: boolean
) {
    const handler = (event: Event) => {
        const targets = Array.isArray(target) ? target : [target]

        if (
            targets.some((item) => {
                const targetElement = item
                return !targetElement || targetElement.contains(event.target as Node)
            })
        ) {
            return
        }

        if (outerVar) {
            onClickAway()
        }
    }

    useEffect(() => {
        if (isListener) {
            window.addEventListener(eventName, handler, useCapture)
        } else {
            window.removeEventListener(eventName, handler, useCapture)
        }

        return () => {
            window.removeEventListener(eventName, handler, useCapture)
        }
    }, [target])
}